package com.ErpCoreWeb.View;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ErpCoreModel.Framework.CBaseObject;
import com.ErpCoreModel.Framework.CColumn;
import com.ErpCoreModel.Framework.CTable;
import com.ErpCoreModel.Framework.Util;
import com.ErpCoreModel.UI.CColumnInView;
import com.ErpCoreModel.UI.CColumnInViewDetail;
import com.ErpCoreModel.UI.CView;
import com.ErpCoreModel.UI.CViewDetail;
import com.ErpCoreWeb.Common.Global;

/**
 * Servlet implementation class MasterDetailViewInfo3
 */
@WebServlet("/MasterDetailViewInfo3")
public class MasterDetailViewInfo3 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	HttpServletRequest request;
	HttpServletResponse response;

    public CView m_View = null;
    public UUID m_Catalog_id = Util.GetEmptyUUID();
    boolean m_bIsNew = false; 
    public CTable m_MTable = null;
    public CTable m_DTable = null;  
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MasterDetailViewInfo3() {
        super();
        // TODO Auto-generated constructor stub
    }

    //初始化变量
    void initData()
    {
        if (request.getSession().getAttribute("User") == null)
        {
            try {
            	response.getWriter().print("请重新登录！");
            	response.getWriter().close();
            	//response.getWriter().print("{success:false,err:'',url:'../Login.jsp'}");
				//response.sendRedirect("../Login.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return ;
        }
		
		String id = request.getParameter("id");
        if (!Global.IsNullParameter(id))
        {
            m_View = (CView)Global.GetCtx(this.getServletContext()).getViewMgr().Find(Util.GetUUID(id));
        }
        else
        {
            m_bIsNew = true;
            if (request.getSession().getAttribute("NewMasterDetailView") == null)
            {
            	try {
            		response.getWriter().print("时间超时！");
                	response.getWriter().close();
        	        return ;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                return ;
            }
            else
            {
            	Map<UUID, CView> sortObj = (Map<UUID, CView>)request.getSession().getAttribute("NewMasterDetailView");
                m_View =(CView) sortObj.values().toArray()[0];
            }
        }
        
        m_MTable = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(m_View.getFW_Table_id());
        CViewDetail ViewDetail = (CViewDetail)m_View.getViewDetailMgr().GetFirstObj();
        if (ViewDetail == null)
        {
            try {
            	response.getWriter().print("时间超时！");
            	response.getWriter().close();
    	        return ;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            return;
        }
        m_DTable = (CTable)Global.GetCtx(this.getServletContext()).getTableMgr().Find(ViewDetail.getFW_Table_id());

        
        String catalog_id = request.getParameter("catalog_id");
        if (!Global.IsNullParameter(catalog_id))
        {
            m_Catalog_id = Util.GetUUID(catalog_id);
        }
    }
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doProc(request,response);
	}
	void doProc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{

		this.request=request;
		this.response=response;

		response.setContentType("text/html;charset=UTF-8");
		request.setCharacterEncoding("UTF-8");

		//初始化变量
	    initData();
	    //
        String Action = request.getParameter("Action");
        if (Action == null) Action = "";

        if (Action.equalsIgnoreCase("GetData"))
        {
        	GetData();
            return ;
        }
        else if (Action.equalsIgnoreCase("GetDetail"))
        {
        	GetDetail();
            return ;
        }
        else if (Action.equalsIgnoreCase("PostData"))
        {
        	PostData();
            return ;
        }
        else if (Action.equalsIgnoreCase("Cancel"))
        {
        	request.getSession().setAttribute("NewMasterDetailView", null);
            return ;
        }
	}
	void GetData()
    {
        List<CBaseObject> lstObj = m_View.getColumnInViewMgr().GetList();
        List<CColumnInView> sortObj = new ArrayList<CColumnInView>();
        for (CBaseObject obj : lstObj)
        {
            CColumnInView civ = (CColumnInView)obj;
            sortObj.add(civ);
        }
        Collections.sort(sortObj, new Comparator<CBaseObject>() {  
            public int compare(CBaseObject o1, CBaseObject o2) {  
                int result = o1.m_arrNewVal.get("idx").IntVal - o2.m_arrNewVal.get("idx").IntVal;  
                return result;  
            }  
        }); 

        String sData = "";

        int iCount = 0;
        for(CColumnInView civ : sortObj)
        {
            CColumn col = (CColumn)m_MTable.getColumnMgr().Find(civ.getFW_Column_id());
            if (col == null)
                continue;

            sData += String.format("{ \"id\": \"%s\",\"ColName\":\"%s\",\"Caption\":\"%s\"},"
                , civ.getId().toString(), col.getName(), civ.getCaption());

            iCount++;
        }
		if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void GetDetail()
    {
        CViewDetail ViewDetail =(CViewDetail)m_View.getViewDetailMgr().GetFirstObj();
        if (ViewDetail == null)
            return;
        List<CBaseObject> lstObj = ViewDetail.getColumnInViewDetailMgr().GetList();
        List<CColumnInViewDetail> sortObj = new ArrayList<CColumnInViewDetail>();
        for (CBaseObject obj : lstObj)
        {
            CColumnInViewDetail civd = (CColumnInViewDetail)obj;
            sortObj.add(civd);
        }
        Collections.sort(sortObj, new Comparator<CBaseObject>() {  
            public int compare(CBaseObject o1, CBaseObject o2) {  
                int result = o1.m_arrNewVal.get("idx").IntVal - o2.m_arrNewVal.get("idx").IntVal;  
                return result;  
            }  
        }); 

        String sData = "";

        int iCount = 0;
        for (CColumnInViewDetail civd : sortObj)
        {
            CColumn col = (CColumn)m_DTable.getColumnMgr().Find(civd.getFW_Column_id());
            if (col == null)
                continue;

            sData += String.format("{ \"id\": \"%s\",\"ColName\":\"%s\",\"Caption\":\"%s\"},"
                , civd.getId().toString(), col.getName(), civd.getCaption());

            iCount++;
        }
		if (sData.endsWith(","))
			sData = sData.substring(0, sData.length() - 1);
        sData = "[" + sData + "]";
        String sJson = String.format("{\"Rows\":%s,\"Total\":\"%d\"}"
            , sData, iCount);

        try {
			response.getWriter().print(sJson);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    void PostData()
    {
		try {
			String GridData = request.getParameter("GridData");
			if (Global.IsNullParameter(GridData)) {
				response.getWriter().print("主表字段不能空！");
				return;
			}
			String GridData2 = request.getParameter("GridData2");
			if (Global.IsNullParameter(GridData2)) {
				response.getWriter().print("从表字段不能空！");
				return;
			}

			String[] arr1 = GridData.split(";");
			for (int i = 0; i < arr1.length; i++) {
				String[] arr2 = arr1[i].split(":");

				CColumnInView civ = (CColumnInView) m_View.getColumnInViewMgr()
						.Find(Util.GetUUID(arr2[0]));
				civ.setCaption(arr2[1]);
				civ.setIdx(i);
				m_View.getColumnInViewMgr().Update(civ);
			}

			CViewDetail ViewDetail = (CViewDetail) m_View.getViewDetailMgr()
					.GetFirstObj();
			arr1 = GridData2.split(";");
			for (int i = 0; i < arr1.length; i++) {
				String[] arr2 = arr1[i].split(":");

				CColumnInViewDetail civd = (CColumnInViewDetail) ViewDetail
						.getColumnInViewDetailMgr().Find(Util.GetUUID(arr2[0]));
				civd.setCaption(arr2[1]);
				civd.setIdx(i);
				ViewDetail.getColumnInViewDetailMgr().Update(civd);
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
    
}
